﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using wps_demo.Models;
using wps_demo.Utils;

namespace wps_demo.Controller
{
    public class WPSFileController : ApiController
    {
        [HttpGet, Route("v1/3rd/file/info")]
        public JsonResult<JObject> FileInfo()
        {
            LogHelper.Info("进入v1/3rd/file/info");
            string filename = string.Empty;
            string fileId = string.Empty;
            HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
            if (httpContextBase == null)
            {
                return null;
            }

            HttpRequestBase request = httpContextBase.Request;
            string permission = "write";
            if (request["_w_permission"] != null)
            {
                permission = request["_w_permission"].ToString();
            }
            if (request["_w_fname"] != null)
            {
                filename = request["_w_fname"].ToString();
            }
            LogHelper.Info("filename："+filename);
            fileId = request.Headers["x-weboffice-file-id"];
            LogHelper.Info("x-weboffice-file-id：" + fileId);
            JObject jsonObject = new JObject();
            JObject file = new JObject();
            JObject user = new JObject();
            try
            {
                WPS_File fileModel = new WPS_File()
                {
                    ID = "1",
                    SIZE = 2000,
                    CREATOR = "wangwc",
                    EDITOR = "wwc",
                    VERSION = 1,
                    DOWNLOAD_URL = WPS_Config.Download_host
                };
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timeStamp = Convert.ToInt64(ts.TotalSeconds);
                file.Add("id", fileModel.ID);
                file.Add("name", filename);
                file.Add("version", 1);
                file.Add("size", fileModel.SIZE);
                file.Add("creator", fileModel.CREATOR);
                file.Add("create_time", timeStamp);
                file.Add("modifier", fileModel.EDITOR);
                file.Add("modify_time", timeStamp);
                file.Add("download_url", fileModel.DOWNLOAD_URL + "/weboffice/getFile?filename=" + filename);
                LogHelper.Info("download_url：" + file["download_url"].ToString());
                jsonObject.Add("file", file);

                WPS_User userModel = new WPS_User()
                {
                    ID = "10",
                    NAME = "wangwc",
                    AVATAR_URL = "https://picsum.photos/100/100/?image=1"
                };
                user.Add("id", userModel.ID);
                user.Add("name", userModel.NAME);
                user.Add("permission", permission);
                user.Add("avatar_url", userModel.AVATAR_URL);
                jsonObject.Add("user", user);
                LogHelper.Info("jsonObject：" + jsonObject.ToString());
            }
            catch (Exception e)
            {
                LogHelper.Error(e.Message);
            }
            LogHelper.Info("离开v1/3rd/file/info");
            return Json(jsonObject);
        }

        [HttpPost, Route("v1/3rd/file/new")]
        public JsonResult<JObject> NewFile()
        {
            try
            {
                LogHelper.Info("进入v1/3rd/file/new");
                JObject obj = new JObject();
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {

                    return null;
                }
                HttpRequestBase request = httpContextBase.Request;
                string fileId = Guid.NewGuid().ToString();
                string filename = request["name"];
                WPS_File fileModel = new WPS_File();
                if (request.Files.Count > 0)
                {
                    HttpPostedFileBase file = request.Files[0];
                    fileModel.ID = Guid.NewGuid().ToString();
                    fileModel.NAME = filename;
                    fileModel.SIZE = file.ContentLength;
                    fileModel.VERSION = 1;
                    fileModel.DOWNLOAD_URL = WPS_Config.Download_host + "/weboffice/getFile?filename=" + filename;
                    string filePath = HttpContext.Current.Server.MapPath("~/") + "File\\" + filename;
                    LogHelper.Info("filePath：" + filePath);
                    file.SaveAs(filePath);
                    LogHelper.Info("download_url：" + fileModel.DOWNLOAD_URL);
                }

                string param = "_w_appid=" + WPS_Config.AppId + "&_w_fname=" + filename; ;
                String signature = WpsUtils.getSignature(WpsUtils.paramToMap(param), WPS_Config.AppKey);
                string url = WPS_Config.Domain + "/office/w/" + fileModel.ID + "?";
                url += param + "&_w_signature=" + signature;
                obj["redirect_url"] = url;
                obj["user_id"] = "wangwc";
                LogHelper.Info("redirect_url：" + url);
                LogHelper.Info("离开v1/3rd/file/new");
                return Json(obj);
            }
            catch (Exception e)
            {
                LogHelper.Error(e.Message);
            }
            return null;
        }

        [HttpGet, Route("v1/3rd/file/version/:{version}")]
        public JsonResult<JObject> Version()
        {
            LogHelper.Info("进入v1/3rd/file/version");
            try
            {
                JObject jsonObject = new JObject();
                JObject file = new JObject();
                JObject user = new JObject();
                try
                {
                    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                    long timeStamp = Convert.ToInt64(ts.TotalSeconds);
                    string filename = "1.doc";
                    WPS_File fileModel = new WPS_File();
                    file.Add("id", 1);
                    file.Add("name", filename);
                    file.Add("version", 1);
                    file.Add("size", 2000);
                    file.Add("creator", "wangwc");
                    file.Add("create_time", timeStamp);
                    file.Add("modifier", "wwc");
                    file.Add("modify_time", timeStamp);
                    file.Add("download_url", WPS_Config.Download_host + "/weboffice/getFile?filename=" + filename);
                    jsonObject.Add("file", file);
                    WPS_User userModel = new WPS_User();
                    user.Add("id", userModel.ID);
                    user.Add("name", userModel.NAME);
                    user.Add("permission", "write");
                    user.Add("avatar_url", userModel.AVATAR_URL);
                    jsonObject.Add("user", user);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
                LogHelper.Info("离开v1/3rd/file/version");
                return Json(jsonObject);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
            }
            return null;
        }

        [HttpPost, Route("v1/3rd/file/online")]
        public void Online()
        {
            LogHelper.Info("进入v1/3rd/file/online");
            LogHelper.Info("离开v1/3rd/file/online");
        }

        [HttpPost, Route("v1/3rd/file/save")]
        public JsonResult<WPS_File> SaveFile()
        {
            LogHelper.Info("进入v1/3rd/file/save");
            WPS_File fileModel = new WPS_File();
            try
            {
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {

                    return null;
                }
                HttpRequestBase request = httpContextBase.Request;
                string fileId = request.Headers["x-weboffice-file-id"];
                LogHelper.Info("fileId：" + fileId);
                long version = DateTime.Now.Minute + DateTime.Now.Second;
                string filename = fileId + "_v" + version + ".doc";
                LogHelper.Info("HttpContext.Current.Server.MapPath：" + HttpContext.Current.Server.MapPath("~/"));

                if (request.Files.Count > 0)
                {
                    HttpPostedFileBase file = request.Files[0];
                    fileModel.ID = Guid.NewGuid().ToString();
                    fileModel.NAME = filename;
                    fileModel.SIZE = file.ContentLength;
                    fileModel.VERSION = version;
                    fileModel.DOWNLOAD_URL = WPS_Config.Download_host + "/weboffice/getFile?filename=" + filename;
                    string filePath = HttpContext.Current.Server.MapPath("~/") + "File\\" + filename;
                    LogHelper.Info("filePath：" + filePath);
                    file.SaveAs(filePath);
                    LogHelper.Info("download_url：" + fileModel.DOWNLOAD_URL);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("v1/3rd/file/save：" + ex.Message);
            }
            LogHelper.Info("离开v1/3rd/file/save");
            return Json(fileModel);
        }

        [HttpGet, Route("weboffice/getFile")]
        public HttpResponseMessage DownLoadFile()
        {
            LogHelper.Info("进入weboffice/getFile");
            try
            {
                string filename = string.Empty;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return null;
                }
                HttpRequestBase request = httpContextBase.Request;
                filename = request["filename"].ToString();
                LogHelper.Info("filename：" + filename);
                if (string.IsNullOrEmpty(filename))
                {
                    return null;
                }
                string filePath = HttpContext.Current.Server.MapPath("~/") + "File\\" + filename;
                LogHelper.Info("filePath：" + filePath);
                FileStream stream = new FileStream(filePath, FileMode.Open);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = HttpUtility.UrlEncode(filename)
                };
                response.Headers.Add("Access-Control-Expose-Headers", "FileName");
                response.Headers.Add("FileName", HttpUtility.UrlEncode(filename));
                LogHelper.Info("离开weboffice/getFile");
                return response;
            }
            catch (Exception ex)
            {

                LogHelper.Error("weboffice/getFile：" + ex.Message);
            }
            return null;
        }

        [HttpPost, Route("v1/3rd/file/history")]
        public JsonResult<JObject> GetHistory()
        {
            try
            {
                LogHelper.Info("进入v1/3rd/file/history");
                JObject result = new JObject();
                JArray jarray = new JArray();
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timeStamp = Convert.ToInt64(ts.TotalSeconds);
                JObject itemObject = new JObject();
                itemObject.Add("id", "1");
                itemObject.Add("name", "1.doc");
                itemObject.Add("version", 1);
                itemObject.Add("size", 1000);
                itemObject.Add("download_url", WPS_Config.Download_host + "/weboffice/getFile?filename=1.doc");
                itemObject.Add("create_time", timeStamp);
                itemObject.Add("modify_time", timeStamp);
 

                JObject creator = new JObject();
                creator.Add("id", "wangwc");
                creator.Add("name", "wangwc_name");
                creator.Add("avatar_url", "https://picsum.photos/100/100/?image=1");
                itemObject.Add("creator", creator);

                creator = new JObject();
                creator.Add("id", "wangwc");
                creator.Add("name", "wangwc_name");
                creator.Add("avatar_url", "https://picsum.photos/100/100/?image=1");
                itemObject.Add("modifier", creator);

                jarray.Add(itemObject);
                result.Add("histories", jarray);
                LogHelper.Info(result.ToString());
                LogHelper.Info("离开v1/3rd/file/history");
                return Json(result);
            }
            catch (Exception e)
            {
                LogHelper.Error(e.Message);
            }
            return null;
        }
       
        [HttpPut, Route("v1/3rd/file/rename")]
        public JsonResult<JObject> Rename() {
            LogHelper.Info("进入v1/3rd/file/rename");
            JObject obj = new JObject();
            obj["name"] = "rename.doc";
            LogHelper.Info("离开v1/3rd/file/rename");
            return Json(obj);
        }
    }
}
